package com.project.servlet;

import com.project.bean.UserBean;
import com.project.service.IUserService;
import com.project.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Enumeration;

public class AddServlet extends HttpServlet {
    private IUserService service  = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //得到多个同名键值对的值，返回数组
//        String[] array =  req.getParameterValues("like");
//        System.out.println(Arrays.toString(array));
        //将表单数据封装成用户对象
        UserBean user = new UserBean();
        this.fullBean(user,req);
        service.add(user);
        resp.getWriter().print("ok");
    }

    private void fullBean(Object beanObj, HttpServletRequest req) {
        //得到表单数据中的表单名枚举
        Enumeration<String> em = req.getParameterNames();
        //得到实体类的类模版
        Class beanClass = beanObj.getClass();

        while(em.hasMoreElements()){//遍历枚举
            String formName = em.nextElement();//取出下一个元素
            //根据表单名，得到表单值
            String value = req.getParameter(formName);

            try {
                //根据属性名，得到属性对象
                Field field = beanClass.getDeclaredField(formName);
                //去掉访问修饰符的检查
                field.setAccessible(true);

                if(field.getType() == String.class) {
                    //给beanObj中指定的属性，赋上value值
                    field.set(beanObj, value);
                }
                else if(field.getType() == LocalDate.class){
                    field.set(beanObj,LocalDate.parse(value));
                }
                else if(field.getType() == int.class || field.getType() == Integer.class){
                    field.set(beanObj,Integer.parseInt(value));
                }
                else if(field.getType() == double.class || field.getType() == Double.class){
                    field.set(beanObj,Double.parseDouble(value));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
